﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WSDZ.KM.ZH.XiaoManIntegrating40
{
    /// <summary>
    /// 小满
    /// </summary>
    [Description("Erp客户推送小满"), HotUpdate]
    public class CustomerManager 
    {
        public string btype = "Erp客户推送小满";
        /// <summary>
        /// 日志文件路径
        /// </summary>
        public string logType = "Erp客户推送小满";
        public string formId = "BD_Customer";
        public TokenData TokenObj = null;

        public string XMUrl = "https://api-sandbox.xiaoman.cn/v1/company/pushCompanyAndCustomers";

        public Context ctx;
        public string date1;
        public string date2;

        public int PageSize = 1000;
        public int AllPage = 1;
   
        Dictionary<string, string> headers;

        public void Main(Context c,string d1,string d2)
        {
            try
            {
                ctx = c;
                date1 = d1;
                date2 = d2;
                var tokens = PostHelper.GetToken(logType);
                if (!tokens.Item1)
                {
                    LogHelper.XiaoManLog($"【获取token错误】【msg:{tokens.Item2.msg}】",logType);
                    return;
                }
                TokenObj = tokens.Item2;
                DealMethod();
            }
            catch (Exception ex)
            {
                LogHelper.XiaoManLog($"【异常A1001】【msg:{ex.Message}】", logType);
            }
        
        }
   
        public void DealMethod()
        {
           
            headers = new Dictionary<string, string>();
            headers.Add("Authorization", $@"Bearer {TokenObj.token}");
            string sql = $@"select 
id=cust.FCUSTID
,number=cust.FNUMBER
,name=custL.FNAME
,isPublic='0'  --是否公海客户
,shortName=custL.FSHORTNAME --简称
,country=countryL.FDATAVALUE  --国家
,tel=cust.FTEL --电话
,poolId='0' --客户公海分组
,address=cust.FADDRESS --客户地址
,remark=custL.FDESCRIPTION --备注
,fax=cust.FFAX --传真
,lxrId=ISNULL(lxr.FCONTACTID,0) --联系人Id
,lxrName=lxrL.FNAME --联系人名称
,email=lxr.FEMAIL --邮箱
,isDefaultLXR=ISNULL(lxr.FISDEFAULTCONTACT,0) --是否默认联系人
,post=lxr.FPOST --职务
,lxrTel=lxr.FMOBILE --联系人电话
from T_BD_CUSTOMER cust
left join T_BD_CUSTOMER_L custL on cust.FCUSTID=custL.FCUSTID and custL.FLOCALEID=2052
left join T_BAS_ASSISTANTDATAENTRY_L countryL on cust.FCOUNTRY=countryL.FENTRYID and countryL.FLOCALEID=2052 --国家
left join T_BD_COMMONCONTACT lxr on cust.FCUSTID=lxr.FCOMPANY and lxr.FCompanyType='BD_Customer' --客户联系人
left join T_BD_COMMONCONTACT_L lxrL on lxr.FCONTACTID=lxrL.FCONTACTID and lxrL.FLOCALEID=2052
where cust.FDOCUMENTSTATUS='C' and ISNULL(cust.F_RLKX_XMCUSTID1,'') in ('','0')";
            DynamicObjectCollection datas = DBUtils.ExecuteDynamicObject(ctx,sql);
            if (datas==null||datas.Count<1)
                return;
            List<Customer> custList = datas.DynamicObjectCollectionToDataList<Customer>();
            Dictionary<int,List<Customer>> custDic = custList.GroupBy(x => x.id).ToDictionary(x=>x.Key,x=>x.ToList());
            foreach (var dic in custDic)
            {
                List<Customer> valueList = dic.Value;
                Customer firstData = valueList.FirstOrDefault();
                try
                {
                    JObject Root = new JObject();
                    Root["name"] = firstData.name;
                    Root["is_public"] = firstData.isPublic;
                    Root["short_name"] = firstData.shortName;
                    Root["tel"] = firstData.tel;
                    Root["pool_id"] = firstData.poolId;
                    Root["address"] = firstData.address;
                    Root["remark"] = firstData.remark;
                    Root["fax"] = firstData.fax;
                    Root["serial_id"] = firstData.number;
                    //客户联系人
                    JArray customerArray = new JArray();
                    foreach (var item in valueList)
                    {
                        if (item.lxrId==0)
                            continue;
                        JObject entyObj = new JObject();
                        entyObj["name"] = item.lxrName;
                        entyObj["email"] = item.email;
                        entyObj["main_customer_flag"] = item.isDefaultLXR;
                        entyObj["post"] = item.post;
                        entyObj["tel"] = item.lxrTel;
                        customerArray.Add(entyObj);
                    }
                    Root["customers"] = customerArray;
                    string json = Root.ToStringV1();
                    string resTxt = PostHelper.Post(XMUrl,json,headers);
                    LogHelper.XiaoManLog($"【更新小满客户】【传入报文】【{json}】\n【返回报文】【{resTxt}】\n\n", logType);
                    JObject resObj = JsonConvert.DeserializeObject<JObject>(resTxt);
                    if (resObj["code"].ToStringV1().EqualsV1("200") && resObj["message"].ToStringV1().EqualsV1("success"))
                    {
                        JObject dataObj = JsonConvert.DeserializeObject<JObject>(resObj["data"].ToStringV1());
                        string companyId = dataObj["company_id"].ToStringV1();
                        string sql_u = $@"update T_BD_CUSTOMER set F_RLKX_XMCUSTID1='{companyId}' where FCUSTID={dic.Key}";
                        DBUtils.Execute(ctx,sql_u);
                    }

                }
                catch (Exception ex)
                {
                    LogHelper.XiaoManLog($"【异常A1002】【客户编码：{firstData.number}】【msg:{ex.Message}】", logType);
                    continue;
                }

            }









        }




    }
}
